package org.zlex.chapter03;

import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;

/**
 * @author : wushikai
 * <p>
 * date : 2021-04-22
 */
public class KeyDemo {


    /**
     * 各种 key 之间的关联;
     * KeyPairGenerator -> KeyPair  -> KeyFactory  [ keyPair.getPrivate().getEncoded(); + X509EncodedKeySpec(其他 spec )]  -> PrivateKey  PublicKey
     * */
    private   static void info ( ) throws NoSuchAlgorithmException, InvalidKeySpecException {


        KeyPairGenerator gen =  KeyPairGenerator.getInstance("RSA");


        gen.initialize(1024);

        KeyPair keyPair = gen.genKeyPair();

        byte[] privateByte = keyPair.getPrivate().getEncoded();

        // 报错 => java.security.spec.InvalidKeySpecException: Only RSAPublicKeySpec and X509EncodedKeySpec supported for RSA public keys
        // PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateByte);
        X509EncodedKeySpec pkcs8EncodedKeySpec = new X509EncodedKeySpec(privateByte);

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");


        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);


        Key publicKey= keyFactory.generatePublic(pkcs8EncodedKeySpec);





    }


    public static void main(String[] args) throws InvalidKeySpecException, NoSuchAlgorithmException {

        info();
    }



}
